package com.utonw.carloan.net;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.utonw.carloan.R;
import com.utonw.carloan.function.UIFunction;
import com.utonw.carloan.global.Constants;
import com.utonw.carloan.app.MyApplication;
import com.utonw.carloan.utils.LogUtil;
import com.utonw.carloan.utils.SharedPreferencesUtils;
import com.utonw.carloan.utils.UIUtils;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

class OkHttp implements NetInterface {
    private OkHttpClient mOkHttpClient;
    private Handler mHandler;
    private Gson mGson;
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private UIFunction mUIFunction;

    OkHttp() {
        //初始化Gson对象
        mGson = new Gson();
        //初始化Handler
        mHandler = new Handler(Looper.getMainLooper());
        //初始化Client对象
        mOkHttpClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(5, TimeUnit.SECONDS)
                .cache(new Cache(Environment.getExternalStorageDirectory(), 10 * 1024 * 1024))
                .build();

        mUIFunction = new UIFunction();

    }

    @Override
    public <T> void startRequest(Context context, final Boolean isShowLoading, String url, Map map, final Class<T> tClass, final NetCallBack<T> callBack) {
        final String jsonStr = mGson.toJson(map);
        RequestBody requestBody = RequestBody.create(JSON, jsonStr);
        Request request = new Request.Builder().url(url)
                .post(requestBody)
                .addHeader("Content-Type", Constants.CONTENT)
                .addHeader(Constants.TOKEN, SharedPreferencesUtils.getToken(MyApplication.getContext()))
                .build();
        if (isShowLoading) {
            mUIFunction.showProgressDialog(context, "请稍等");
        }

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (isShowLoading) {
                            mUIFunction.dissmissProgressDialog();
                        }
                        UIUtils.showShortToast(UIUtils.getString(R.string.net_error));
                        callBack.onError(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final T result;
                final String str = response.body().string();
                if (isShowLoading) {
                    mUIFunction.dissmissProgressDialog();
                }
                try {
                    result = mGson.fromJson(str, tClass);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callBack.onSuccess(result);
                        }
                    });

                } catch (final Throwable e) {

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callBack.onError(e);
                            UIUtils.showShortToast(UIUtils.getString(R.string.data_error));
                            LogUtil.d(str);
                        }
                    });

                }


            }
        });
    }
}
